import { PrismaClient } from "@prisma/client"
import bc from "bcryptjs"
const p = new PrismaClient()

export default {
    login(req,res){
        res.render("login")
    },
    async doLogin(req,res){
       const email = req.body.email ?? ""
       const password = req.body.password ?? ""
       const user = await p.user.findFirst({
        where: {email}
       })
       if(user && bc.compareSync(req.body.password,user.password)){
            // 如果有登录前想要前往的页面，前往该页面，否则到首页
            delete user.password
            req.session.user = user
            if(req.session.attended){
                res.redirect(req.session.attended)
            }
            else{
                res.redirect("/")
            }
       }
       else{
            // 登录失败，返回登录页面
            req.session.email = email
            res.redirect("/login")
       }
    },
    logout(req,res){
        req.session.regenerate((err)=>{
            res.redirect("/")
        }) 
    }
}